<?php

namespace app\common\command;

use app\common\classes\helper\SendMessage;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\Db;

class PaymentAlarm extends Command
{

    protected function configure()
    {
        $this->setName('payment_alarm')
            ->addArgument('action', Argument::OPTIONAL, "方法名称")
            ->setDescription('支付报警');
    }

    protected function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');
        $this->$action();
    }

    public function handler()
    {
        $list = Db::table('quick_payment_number')->where('baojing_switch', 1)->column('baojing_minute','id');
        $templateCode = 'SMS_465360097';
        $signName = '九霄书屋';
        $phones = Db::table("quick_payment_alarm")->column('phone');
        foreach ($list as $payId => $value) {
            $create_time = Db::table('pay_order')->where([['chargefrom', '=', $payId],['status', '=', 2]])->order("create_time desc")->value('create_time');
            $kl_create_time = Db::table('pay_order_kl_backups')->where([['chargefrom', '=', $payId],['status', '=', 2]])->order("create_time desc")->value('create_time');
            if ($create_time) {
                $lastPayTime = strtotime($create_time);
            } else {
                $lastPayTime = 0;
            }

            if ($kl_create_time) {
                $kl_lastPayTime = strtotime($kl_create_time);
            } else {
                $kl_lastPayTime = 0;
            }

            $intervalTime = time() - $lastPayTime;//充值时间间隔
            $kl_intervalTime = time() - $kl_lastPayTime;//充值时间间隔
            if ($intervalTime >= $value * 60 && $kl_intervalTime >= $value * 60) {
                $sendTime = intval($intervalTime / 60);
                // 查询无支付订单数量
                $noPayWhere = [];
                $noPayWhere[] = ['chargefrom', '=', $payId];
                $noPayWhere[] = ['status', '=', 1];
                $noPayWhere[] = ['create_time', '>', $create_time];
                $count = Db::table('pay_order')->where($noPayWhere)->group("uid")->count();
                $klCount = Db::table('pay_order_kl_backups')->where($noPayWhere)->group("uid")->count();
                foreach ($phones as $phone) {
                    $argv = [
                        "phoneNumbers" => $phone,
                        "signName" => $signName,
                        "templateCode" => $templateCode,
                        "templateParam" => "{\"name\":\"" . $payId . "\",\"time\":\"" . $sendTime . "\",\"count\":\"" . ($count+$klCount) . "\"}"
                    ];
                    SendMessage::main($argv, 'LTAI5tJZJRpKWvmjLT6fFRnC', 'pjdwafj13YtbssTEWgQrhrK5kAQcIC');
                }
            }
        }
    }
}